package ext.tianma.bom.service;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.httpgw.URLFactory;
import wt.inf.container.WTContainer;
import wt.part.WTPart;
import wt.pom.PersistenceException;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc.VersionReference;
import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.part.MyPartUtil;

public class SelectPartService {
	/**
	 * 通过物料编号，视图，查询最新版本物料信息
	 * 
	 * @param productNumber
	 * @param view
	 * @return
	 * @throws JSONException 
	 */
	public static String getNewestPartMessageByNumberAndView(
			String productNumber, String view) throws JSONException {
		JSONObject ob = new JSONObject();
		JSONArray array = new JSONArray();
		try {
			if (null != view && !"".equals(view)) {
				WTPart part = CoreUtil.getWTPartByNumberAndView(productNumber,
						view);
				if(part != null) {
					getPart(productNumber, view, ob, array, part);
				}else {
					ob.put("status", "false");
					ob.put("message", "未查到！");
				}
			} else {
				List<WTPart> list = getAllLatestVersionPart(productNumber);
				if(list.size()>0) {
					for (int i = 0; i < list.size(); i++) {
						WTPart part = list.get(i);
						String viewName = part.getViewName();
						if (!"Design".equalsIgnoreCase(viewName)) {
							getPart(productNumber, viewName, ob, array, part);
						}
					}
				}else {
					ob.put("status", "false");
					ob.put("message", "未查到！");
				}
				
			}
		} catch (Exception e) {
			ob.put("status", "error");
			ob.put("message", "接口错误！");
			e.printStackTrace();
		}
		return ob.toString();

	}

	/**
	 * 将part详细信息放入json
	 * 
	 * @param productNumber
	 * @param view
	 * @param ob
	 * @param array
	 * @param part
	 * @throws PersistenceException
	 * @throws WTException
	 * @throws JSONException
	 * @throws RemoteException 
	 */
	public static void getPart(String productNumber, String view,
			JSONObject ob, JSONArray array, WTPart part)
			throws PersistenceException, WTException, JSONException, RemoteException {
		String productName = part.getName();// 物料名称
		String productInfoUrl = generateInfoPageURL(part);// 物料信息页面url
		String createBy = CommonPDMUtil.getCreatorFullName(part);// 创建者
		String createTime = CommonPDMUtil.getCreateTime(part);// 创建时间
		String updateBy = CommonPDMUtil.getModifierName(part);// 修改者
		String updateTime = CommonPDMUtil.getModifyTime(part);// 修改时间
		String productState = part.getState().getState().getDisplay(Locale.CHINA);// 状态
		//addby xucr on 2020.11.02  接口添加模组研发地、panel研发地字段
		String modulePlace =  (String) IBAUtil.getIBAValue(part, "modulesDevelopedLand"); // 模组研发地
		String panelPlace =  (String) IBAUtil.getIBAValue(part, "panelDevelopedLand"); // panel研发地
		
		ob.put("status", "success");
		ob.put("message", "查询成功!");
		JSONObject ob1 = new JSONObject();
		ob1.put("productNumber", productNumber);
		ob1.put("productName", productName);
		ob1.put("view", view);
		ob1.put("productInfoUrl", productInfoUrl);
		ob1.put("createBy", createBy);
		ob1.put("createTime", createTime);
		ob1.put("updateBy", updateBy);
		ob1.put("updateTime", updateTime);
		ob1.put("productState", productState);
		ob1.put("modulePlace", modulePlace);
		ob1.put("panelPlace", panelPlace);
		array.put(ob1);
		ob.put("data", array);
	}

	/**
	 * 根据part得到物料信息页面url
	 * 
	 * @param part
	 * @return
	 * @throws PersistenceException
	 * @throws WTException
	 */
	public static String generateInfoPageURL(WTPart part)
			throws PersistenceException, WTException {
		String url = "";
		ReferenceFactory referenceFactory = new ReferenceFactory();
		URLFactory urlfactory = new URLFactory();
		String baseHref = urlfactory.getBaseHREF();
		if (part != null && part.getNumber() != null) {
			WTContainer container = part.getContainer();
			String ufid = referenceFactory.getReferenceString(VersionReference
					.newVersionReference((Iterated) part));
			String containerOid = "";
			if (container != null) {
				containerOid = referenceFactory.getReferenceString(container);
			}
			if ("".equals(containerOid)) {
				url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid
						+ "&u8=1";
			} else {
				url = baseHref + "app/#ptc1/tcomp/infoPage?ContainerOid="
						+ containerOid + "&oid=" + ufid + "&u8=1";
			}
		}
		return url;
	}

	/**
	 * 通过number获取最新大版本物料
	 * 
	 * @param number
	 * @return
	 */

	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class,
					WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression(
					"A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper
						.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = MyPartUtil.getWTPartByNumViewAndVersion(
						part.getNumber(), part.getView().getName(), v);
				if (null != p) {
					continue;
				}
				list.add(part);
			}
		} catch (Exception e) {
		}
		return list;
	}

}
